import type { ComputedRef, Ref } from 'vue'
import type { TableProps, ColumnType } from '../types'
import type { IndexType } from '../../grid/types'

import { DEFAULT_CELL_WIDTH, DEFAULT_CELL_HEIGHT } from '../../grid/constants'
import { getHeaderDepth } from '../../helper'

const useTable = (
  props: TableProps,
  getColumns: ComputedRef<ColumnType[]>,
  getFlattenedColumns: ComputedRef<ColumnType[]>,
  columnsWidthRef: Ref<Record<string, number>>
) => {
  function getCellKey({ rowIndex, columnIndex }: IndexType) {
    return `ROW_${rowIndex}_COLUMN_${columnIndex}`
  }

  function getHeaderCellKey({ rowIndex, columnIndex }: IndexType) {
    return `HEADER_ROW_${rowIndex}_COLUMN_${columnIndex}`
  }

  function getColumnWidth(index: number) {
    return (
      columnsWidthRef.value[getFlattenedColumns.value[index].field] ||
      getFlattenedColumns.value[index].width ||
      DEFAULT_CELL_WIDTH
    )
  }

  function getRowHeight(index: number) {
    const rowHeight =
      typeof props.rowHeight === 'function'
        ? props.rowHeight(index)
        : props.rowHeight || DEFAULT_CELL_HEIGHT
    return rowHeight
  }

  function getHeaderRowHeight() {
    const rowHeight = props.headerHeight || DEFAULT_CELL_HEIGHT
    const multipleLevelColumns = getColumns.value.filter(
      (col) => col.children && col.children.length > 0
    )
    const depth = getHeaderDepth(multipleLevelColumns)
    return rowHeight * depth
  }

  return {
    getCellKey,
    getHeaderCellKey,
    getColumnWidth,
    getRowHeight,
    getHeaderRowHeight
  }
}

export default useTable
